package com.tbit.main.remote.map;

import com.alibaba.fastjson.JSONObject;
import com.tbit.common.utils.GDMapUtil;
import com.tbit.main.constant.SysConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;

/**
 * 腾讯地图
 *
 * @author Leon
 * 2019年11月15日 下午2:28:31
 */
@Slf4j
public class TXHttpClient {
    private static HttpClient client = null;


    /**
     * 维持单session
     */
    public static HttpClient getClient() {
        if (client == null) {
            MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
            client = new HttpClient(connectionManager);
            /**设置编码*/
            client.getParams().setContentCharset("UTF-8");
            /**请求超时*/
            client.getHttpConnectionManager().getParams().setConnectionTimeout(1000);
            /**读取超时*/
            client.getHttpConnectionManager().getParams().setSoTimeout(5000);
        }
        return client;
    }

    /**
     * 查询地址
     */
    public static String getAddress(Double lo, Double ln) {
        //因为引用的地方比较多，直接在此进行判断开关是否使用高德
        if (SysConstant.GD_MAP_SWITCH) {
            return GDMapUtil.getAddress(lo, ln, SysConstant.GD_MAP_KEY);
        }
        HttpClient client = getClient();
        GetMethod get = null;
        String address = null;
        try {
            get = new GetMethod("https://apis.map.qq.com/ws/geocoder/v1/?get_poi=0&key=" + SysConstant.QQ_key + "&location=" + ln + "," + lo);
            client.executeMethod(get);
            String result = get.getResponseBodyAsString();
            JSONObject object = JSONObject.parseObject(result);
            Integer state = object.getInteger("status");
            System.out.println(object);
            if (state == 0) {
                address = object.getJSONObject("result").getString("address");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        } finally {
            get.releaseConnection();
        }
        return address;
    }

    public static void main(String[] args) {
        System.out.println(getAddress(114.4094389013507, 30.456475531638162));
    }
}